package com.leyou.cart.inteceptors;

import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.cart.config.JwtProperties;
import com.leyou.common.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 *
 * 获取登录的信息
 *
 */


@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProps;

    // 定义一个线程域，存放登录用户(线程安全的)
    private static final ThreadLocal<UserInfo> tl = new ThreadLocal<>();


    //前置方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = CookieUtils.getCookieValue(request, jwtProps.getCookieName());

        UserInfo user = JwtUtils.getInfoFromToken(token, jwtProps.getPublicKey());

        tl.set(user);
        return true;//如果是false将在这里停止不前
    }

    //最终执行,把存入到tl中所有信息带走
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        tl.remove();
    }

    //定义一个静态方法使得在外界可以获取到userInfo

    public static UserInfo getUserInfo(){
        return tl.get();
    }
}
